package com.founder.helloworldapp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class LocationsActivity extends Activity {
	
	private ListView locationListView;
	
	private List<Map<String, String>> locationData;
	
	private SimpleAdapter adapter;
	
	private DatabaseHelper dbHelper;
	
	private long trackId;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_list);
        dbHelper = new DatabaseHelper(this);
        
        trackId = Long.parseLong(getIntent().getStringExtra("trackId"));
        locationListView = (ListView)findViewById(R.id.locationListView);
        locationData = new ArrayList<Map<String, String>>();
        adapter = new SimpleAdapter(this, locationData, R.layout.location_list_item, 
        		new String[] {"titleText", "subTitleText"}, new int[] {R.id.titleText,R.id.subTitleText});
        locationListView.setAdapter(adapter);
        
        loadLocations();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
    }
    
    private void loadLocations() {
    	final int size = 500;
    	List<Location> locations = dbHelper.queryLocations(trackId, size);
    	for (Location location : locations) {
    		locationData.add(initMap(location));
    	}
    	adapter.notifyDataSetChanged();
    }
    
    private String formatDate(long time) {
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return df.format(new Date(time));
    }
    
    private String formatDouble(double number) {
    	return String.format("%.4f", number);
    }
    
    private Map<String, String> initMap(Location l) {
    	Map<String, String> data = new HashMap<String, String>();
		data.put("titleText", formatDate(l.getTime()));
		data.put("subTitleText", l.getProvider() + "(" + formatDouble(l.getLatitude()) + "," + formatDouble(l.getLongitude()) + "," + l.getAccuracy() +")");
		return data;
    }
}
